package com.chtwm.redis.sync.service;

import com.chtwm.redis.sync.config.SyncConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 自己实现一个Redis协议
 */
@Slf4j
@Data
public class MyRedisSocketService {

    private SyncConfig syncConfig;

    public MyRedisSocketService(SyncConfig syncConfig) {
        this.syncConfig = syncConfig;
    }

    /**
     * 同步所有
     */
    public void syncAll() throws IOException {
        Socket socket = new Socket();
        socket.setReuseAddress(true);
        socket.setKeepAlive(true);
        socket.setTcpNoDelay(true);
        socket.connect(new InetSocketAddress("192.168.10.10", 7006), 6000);

        OutputStream os = socket.getOutputStream();
        String command = "*1\r\n$4\r\nPING\r\n";
        /*os.write('*');
        os.write("1".getBytes());
        os.write('\r');
        os.write('\n');
        os.write('$');
        os.write("4".getBytes());
        os.write('\r');
        os.write('\n');
        os.write("PING".getBytes());
        os.write('\r');
        os.write('\n');*/

        os.write(command.getBytes());
        os.flush();
        int i = 0;
        String ret = "";
        byte[] bytes = new byte[1024];
        InputStream is = socket.getInputStream();

        while ((i = is.read(bytes)) > 0) {
            ret += new String(bytes);
            log.info("ret-{}", ret);
        }

        log.info("返回结果-{}", ret);
    }

}
